package com.isslin.client;

import com.isslin.client.handler.ClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyClient {

    private static Bootstrap bootstrap = null;

    public NettyClient() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                // 编码器
                                //.addLast(new AjaxEncoder())
                                //.addLast(new AjaxDecoder())
                                .addLast(new StringEncoder())
                                .addLast(new StringDecoder())
                                .addLast(new ClientHandler());
                    }
                });
        connect();
    }

    public static void connect() {
        try {
            System.out.println("正在连接服务器...");
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8989).sync();
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        System.out.println("服务连接成功");
                    } else {
                        System.err.println("服务连接失败");
                    }
                }
            });

            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}
